import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @Description: 最小差值平方和
 * @Date:Create in 22:44 2022/7/9
 */
public class minSumSquareDiff {
    public static void main(String[] args) {
//        int[] nums1 = {7,11,4,19,11,5,6,1,8};
//        int[] nums2 = {4,7,6,16,12,9,10,2,10};
//        int[] nums1 = {1, 4, 10, 12};
//        int[] nums2 = {5, 8, 6, 9};
//        int[] nums1 = {20,19,3,18,16,20,0};
//        int[] nums2 = {39,5,3,1,30,1,14};
        int[] nums1 = {18,4,8,19,13,8};
        int[] nums2 = {18,11,8,2,13,15};
        int k1 = 16;
        int k2 = 8;
        System.out.println(minSumSquareDiff1(nums1, nums2, k1, k2));
    }

    public static long minSumSquareDiff1(int[] nums1, int[] nums2, int k1, int k2) {
        int n = nums1.length;

        int[] nums3 = new int[n];
        for (int i = 0; i < n; i++) {
            nums3[i] = Math.abs(nums1[i] - nums2[i]);
        }

        Arrays.sort(nums3);
//        for(int num:nums3){
//            System.out.println(num);
//        }

        long k = (long) k1 + k2;
        int left = n - 1;

        out:
        while (k > 0 && !isZero(nums3)) {
            int right = 0, detch = 0;
            for (int j = left; j >= 0; j--) {
                if (nums3[j] != nums3[left]) {
                    right = j;
                    detch = nums3[left] - nums3[j];
                    break;
                }
            }
            if (right == 0 && (nums3[0] == nums3[1])) {
                right = -1;
                detch = 1;
            }
            if(k<(left-right)*detch){
                detch = 1;
            }
//            System.out.println(nums3[n-1]);
            for (int m = left; m > right; m--) {
//                System.out.println(nums3[m]);
                if (k - detch <= 0) {
                    nums3[m] -= detch;
                    break out;
                }
                nums3[m] -= detch;
                k -= detch;
            }
            left = n - 1;
//            System.out.println(k);
        }

        long sum = 0;
        for (int num : nums3) {
            sum += (long) num * num;
        }
        return sum;
    }

    public static boolean isZero(int[] nums) {
        for (int num : nums) {
            if (num != 0) return false;
        }
        return true;
    }
}
